<template>
  <ul class="list">
    <li class="item"
    v-for="item of letters"
    :key="item"
    :ref="item"
    @click="handleLetterClick"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
    >
    {{item}}
    </li>
  </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object,
  },
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timer: null,
    };
  },
  updated() {
    //  性能优化：加载完成获取A到顶部的高度
    this.startY = this.$refs.A[0].offsetTop;
  },
  computed: {
    letters() {
      const letters = [];
      if (JSON.stringify(this.cities) !== '{}') {
        let arrs = Object.keys(this.cities);
        for (let i = 0; i < arrs.length; i++) {
          letters.push(arrs[i]);
        }
      }
      return letters;
    },
  },
  methods: {
    handleLetterClick(e) {
      this.$emit('change', e.target.innerText);
    },
    handleTouchStart() {
      this.touchStatus = true;
    },
    handleTouchMove(e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        // 性能优化，函数节流
        this.timer = setTimeout(() => {
          const headerHeight = Math.floor((document.body.clientWidth / 100) * 26); // 工具条到屏幕顶部的距离
          const letterHeight = Math.floor((document.body.clientWidth / 100) * 5); // 每一个字符的高度
          const touchY = e.touches[0].clientY - headerHeight;
          const index = Math.floor((touchY - this.startY) / letterHeight);
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index]);
          }
        }, 16);
      }
    },
    handleTouchEnd() {
      this.touchStatus = false;
    },
  },
};
</script>

<style lang="stylus"  scoped>
  @import '~style/varibles.styl'
  .list
    position : absolute
    right: 0
    top: 26vw
    bottom: 0
    width: 6vw
    .item
      line-height : 5vw
      text-align : center
      color: $bgColor
</style>
